import mongoose from "mongoose";
import {IKline} from "../types";
import Logger from "../common/logger";

class KlineModel {

    public readonly  model: mongoose.Model<IKline>;
    public readonly logger: Logger;
    constructor(db:mongoose.Connection, col_name:string, schema:mongoose.Schema, logger:Logger) {
        this.model = db.model<IKline>(col_name, schema);
        this.logger = logger;

    }
    async getKlineByFilter(filter:Object) {
        try{

            let ret = await  this.model.findOne(filter);
            return ret;
        }catch(e){
            this.logger.error("getKlines e: ",e);
        }

    }
    async getKlinesByFilter(filter:Object) {
        try{

            let ret = await  this.model.find(filter);
            return ret;
        }catch(e){
            this.logger.error("getKlines e: ",e);
        }

    }
    async insertKline( symbol:string, docData:any[]) {
        try{

            let oldDoc = await this.model.findOne({symbol:symbol, openTime: docData[0]});
            console.log('oldDoc: ', oldDoc);
            if(oldDoc === null){
                let doc = new  this.model({
                    symbol:symbol,
                    openTime:docData[0],
                    openPrice:docData[1],
                    highPrice:docData[2],
                    lowPrice:docData[3],
                    closePrice:docData[4],
                    volume:docData[5],
                    closeTime:docData[6],
                    quteAssetVolume:docData[7],
                    numberOftrades:docData[8],
                    takerBuyBaseAssetVolume:docData[9],
                    takerBuyQuoteAssetVolume:docData[10],
                    unUsedField:docData[11],
                });
                let newDoc = await doc.save();
                if(newDoc) {
                    this.logger.debug("updateKlines, symbole: ", symbol, " newDoc: ", newDoc);
                }

            }else{
                this.logger.info("updateKlines data double, symoble: ", symbol, "docData: ", docData);
            }

        }catch(e) {
            this.logger.error("insertKline e: ",e);
        }
    }
    async  updateKline(filter:object, updateDoc:Object){
        try{
            let res = await this.model.updateOne(filter, updateDoc);
            if(res){
                return true;
            }else{
                return false;
            }
        }catch (e) {
            this.logger.error("updateKline e: ",e);
            return false;
        }
    }
    async insertMany(updateDocs:IKline[]){
        try{
            let res = await this.model.insertMany(updateDocs);
            if(res){
                return true;
            }else{
                return false;
            }
        }catch (e) {
            this.logger.error("insertMany, e: ",e);
        }
    }

}

export  default KlineModel;